/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.model.process.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.je.bpm.model.process.model.impl.ObjectValue;
import com.je.bpm.model.process.model.impl.ProcessVariablesMap;
import com.je.bpm.model.process.model.impl.ProcessVariablesMapTypeRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.ConversionService;

import java.io.IOException;

public class ProcessVariablesMapDeserializer extends JsonDeserializer<ProcessVariablesMap<String, Object>> {

    private static final Logger logger = LoggerFactory.getLogger(ProcessVariablesMapDeserializer.class);

    private static final String VALUE = "value";
    private static final String TYPE = "type";
    private final static ObjectMapper objectMapper = new ObjectMapper();
    private final ConversionService conversionService;

    public ProcessVariablesMapDeserializer(ConversionService conversionService) {
        this.conversionService = conversionService;
    }

    @Override
    public ProcessVariablesMap<String, Object> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
            JsonProcessingException {
        ProcessVariablesMap<String, Object> map = new ProcessVariablesMap<>();

        JsonNode node = jp.getCodec().readTree(jp);

        node.fields().forEachRemaining(entry -> {
            String name = entry.getKey();
            JsonNode entryValue = entry.getValue();

            if (!entryValue.isNull()) {
                if (entryValue.get(TYPE) != null && entryValue.get(VALUE) != null) {
                    String type = entryValue.get(TYPE).textValue();
                    String value = entryValue.get(VALUE).asText();

                    Class<?> clazz = ProcessVariablesMapTypeRegistry.forType(type);
                    Object result = conversionService.convert(value, clazz);

                    if (ObjectValue.class.isInstance(result)) {
                        result = ObjectValue.class.cast(result)
                                .getObject();
                    }

                    map.put(name, result);
                } else {
                    Object value = null;
                    try {
                        value = objectMapper.treeToValue(entryValue,
                                Object.class);
                    } catch (JsonProcessingException e) {
                        logger.error("Unexpected Json Processing Exception: ", e);
                    }
                    map.put(name, value);
                }

            } else {
                map.put(name, null);
            }
        });

        return map;
    }
}
